package com.lemon.cloud.admin.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.PhoneUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.lemon.cloud.comm.model.ResultCode;
import com.lemon.cloud.comm.model.ResultMsg;
import com.lemon.cloud.comm.po.SysUser;
import com.lemon.cloud.admin.service.AppService;
import com.lemon.cloud.admin.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

import static com.lemon.cloud.comm.constants.CacheConstants.CODE_PREFIX;
import static com.lemon.cloud.comm.constants.OAuth2Constant.CODE_TIME;

@Service
@Slf4j
public class AppServiceImpl implements AppService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SysUserService sysUserService;

    @Override
    public ResultMsg<Boolean> getSmsCode(String mobile) {
        boolean isPhone = PhoneUtil.isPhone(mobile);
        if (!isPhone){
            return ResultMsg.resultFail(ResultCode.PHONE_ERROR.getCode(),ResultCode.PHONE_ERROR.getMsg());
        }
        long count = sysUserService.count(Wrappers.<SysUser>query().lambda().eq(SysUser::getMobile, mobile));

        if (count<=0) {
            log.info("手机号未注册:{}", mobile);
            return ResultMsg.resultFail(ResultCode.APP_PHONE_UNREGISTERED.getCode(),ResultCode.APP_PHONE_UNREGISTERED.getMsg());
        }

        String s = RandomUtil.randomNumbers(6);
        log.info("验证码为:{}",s);
        ValueOperations operations = redisTemplate.opsForValue();
        operations.set(CODE_PREFIX+mobile,s,CODE_TIME, TimeUnit.SECONDS);
        return ResultMsg.resultSuccess(true);
    }
}
